<template>
  <cs-form
    ref="formRef"
    v-model="store.apiFormData"
    :items="items"
    component-full-width
  />
</template>

<script setup lang="ts">
  import { computed, inject, reactive, toRef } from 'vue'

  import type { ApiFormData, ApiMap, Store } from '../types'

  const store = inject('CSDEV_CODE_VIEW_STORE', {} as Store)

  const formRef = toRef(store, 'apiFormRef')
  const apiMap = reactive<ApiMap>({
    listPage: '列表',
    add: '新增',
    modify: '编辑',
    del: '删除',
    importExcel: '导入',
    downloadImportTemplate: '导入模板',
    exportExcel: '导出'
  })

  /** 当前接口文件下的api */
  const currentApi = computed(() => {
    return store.apis[store.basicFormData.apiFilePath]
  })

  /** 表单项 */
  const items = computed(() => {
    const currentItems: FormItemProps<ApiFormData>[] = []
    for (const functionName in apiMap) {
      const prop = functionName as keyof typeof apiMap
      const apiLabel = apiMap[prop]
      const currentApis = currentApi.value?.apis || {}
      const options: Array<{ label: string, value: string }> = []
      for (const key in currentApis) {
        // 过滤掉用户已选的Api名称
        if (!currentApis[key].choiceFuncName) {
          options.push({
            label: `${key} - ${currentApis[key].desc}`,
            value: key
          })
        }
      }
      currentItems.push({
        label: `【${apiLabel}】接口`,
        prop,
        component: 'cs-select',
        required: prop === 'listPage',
        props: {
          fitInputWidth: true,
          filterable: true,
          options
        }
      })
    }
    return currentItems
  })
</script>
